package com.njcb.ams.bootconfig;

import com.njcb.ams.store.mail.MailServiceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.net.InetAddress;
import java.util.Properties;

/**
 * 构建邮件服务
 * @author liuyanlong
 *
 */
@Configuration
public class SpringMailConfig {
	private static final Logger logger = LoggerFactory.getLogger(SpringMailConfig.class);
	//spring配置邮件服务器 
	@Bean(name = "mailSender")
	public JavaMailSender getMailSender() {
//		String addressStr = "smtp.trythis.cn";
		String addressStr = "";
		try {
			//网络不可用则直接返回空
			InetAddress address = InetAddress.getByName(addressStr);
			if(!address.isReachable(200)){
				return null;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}

		JavaMailSenderImpl javaMail = new JavaMailSenderImpl();
//		javaMail.setProtocol("smtp");
//		javaMail.setHost(addressStr);
//		javaMail.setPort(25);
//		javaMail.setUsername("admin@trythis.cn");
//		javaMail.setPassword("*****");
		Properties javaMailProperties = new Properties();
		javaMailProperties.setProperty("mail.smtp.auth", "true");
//		javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
//		javaMailProperties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    	javaMail.setJavaMailProperties(javaMailProperties);
		return javaMail;
	}

	//并发器
	@Bean(name = "taskExecutor")
	public ThreadPoolTaskExecutor getTaskExecutor() {
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		taskExecutor.setCorePoolSize(5);
		taskExecutor.setMaxPoolSize(10);
		return taskExecutor;
	}
	
	//邮件发送服务提供者
	@Bean(name = "mailServiceManager")
	public MailServiceManager mailServiceManager() {
		MailServiceManager mailServiceManager = new MailServiceManager();
		mailServiceManager.setMailSender(getMailSender());
		mailServiceManager.setTaskExecutor(getTaskExecutor());
		return mailServiceManager;
	}

}
